from rest_framework_simplejwt.authentication import JWTAuthentication
from .helpers import get_authing_client
from .models import User

from rest_framework.permissions import IsAuthenticated

class AuthingIDAuthentication(JWTAuthentication):
    """
    使用Authing在线接口验证Token的合法性,
    并从Token中提取用户信息,用户权限
    """
    #只需重载authenticate方法
    def authenticate(self, request):
        header = self.get_header(request)
        if header is None:
            return None
        raw_token = self.get_raw_token(header)
        raw_token = str(raw_token,encoding='utf-8')
        #在线验证
        client = get_authing_client()
        result = client.validate_token(id_token=raw_token)
        if result.get('code',200) == 400: #无效的TOKEN
            return None
        #此处已取得验证结果,为一个字典,详见authing文档
        #接着根据ID从数据库中返回用户
        user, created = User.objects.get_or_create(authingid=result['sub'])
        user.is_authenticated = True
        return user, None
